import React, { Component } from 'react';
import { Table, Form, Select, Row, Col, Button, Input, InputNumber, Modal, message } from 'antd';
import { Http } from './../common/Utils';
import { FieldRender } from './FieldRender'

const FormItem = Form.Item;
const Option = Select.Option;

/**
 * 提供自动加载的Table
 */
class CrudTable extends Component {

    state = {
        data: [],
        pagination: {
            showSizeChanger: true
        },
        loading: false
    }

    handleTableChange = (pagination, filters, sorter) => {
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;

        this.setState({
            pagination: pager,
        });

        this.fetch({
            pageSize: pagination.pageSize,
            pageNo: pagination.current,
            sortField: sorter.field,
            sortOrder: sorter.order,
            ...filters,
        });
    }

    fetch = (params = {}) => {
        if (!this.props.url) {
            console.error('请传入url');
            return;
        }

        this.setState({ loading: true });

        params = { pageSize: 10, ...params };

        Http.Post(this.props.url, params).then(data => {
            const pagination = { ...this.state.pagination };
            pagination.total = data.total;

            this.setState({
                loading: false,
                data: data.list,
                pagination
            });
        }).catch((e, data) => {
            this.setState({
                loading: false
            });
        });

    }

    componentDidMount() {
        this.fetch();
    }

    render() {
        return (
            <div>
                <Table style={{ height: '100%' }} columns={this.props.columns}
                    size={"middle"}
                    rowKey={record => record.registered}
                    dataSource={this.state.data}
                    pagination={this.state.pagination}
                    loading={this.state.loading}
                    onChange={this.handleTableChange}
                />
            </div>
        );
    }
}

/**
 * 提供自动布局的Toolbar上Form
 */
class AutoToolForm extends React.Component {

    state = {
        colStyle: {
            margin: '5px 0'
        }
    }

    onSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err && this.props.onSearch) {
                this.props.onSearch(values);
            }
        });
    }

    renderAddBtn = () => {
        if (!this.props.hideAdd) {
            return (
                <Col span={2} style={this.state.colStyle}>
                    <Button type="primary" icon="plus" style={{ width: '100%' }} onClick={this.props.onAdd}>
                        添加
                    </Button>
                </Col>
            )
        }
    }

    render() {

        const { getFieldDecorator } = this.props.form;

        return (
            <Form onSubmit={this.onSubmit} layout="inline" style={{ padding: '10px 20px' }}>
                <Row gutter={24}>
                    {this.props.fields.map((field, index) => {
                        if (FieldRender.support(field.type)) {
                            return (
                                <Col key={'toolbar-filed-' + index} span={5} style={this.state.colStyle}>
                                    <FormItem label={field.label}>
                                        {getFieldDecorator(field.name, field.option)(
                                            FieldRender.render(field)
                                        )}
                                    </FormItem>
                                </Col>
                            );
                        }
                    })}
                    <Col span={2} style={this.state.colStyle}>
                        <Button type="primary" icon="search" htmlType="submit" style={{ width: '100%' }}>
                            查询
                        </Button>
                    </Col>
                    {this.renderAddBtn()}
                </Row>
            </Form >
        );
    }
}

/**
 * 自定义工具条,对AutoToolForm进行了包装
 */
class Toolbar extends React.Component {
    render() {
        const Toolbar = Form.create()(AutoToolForm);
        return <Toolbar {...this.props} />
    }
}

/**
 * 提供自动布局的新增/编辑Form
 */
class AutoEidtForm extends React.Component {
    onSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err && this.props.onSearch) {
                this.props.onSearch(values);
            }
        });
    }

    render() {

        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (

            <Form onSubmit={this.onSubmit} layout="horizontal" style={{ padding: '10px 0px' }}>
                <Row gutter={24}>
                    {this.props.fields.map((field, index) => {
                        if (field.type == 'hidden') {
                            return getFieldDecorator(field.name, field.option)(<Input key={'editform-field' + index} type="hidden" />);
                        } else if (FieldRender.support(field.type)) {
                            return (
                                <Col key={'col-edit-' + index + '-' + field.name} span={field.span != null ? field.span : 12}>
                                    <FormItem key={'editform-field' + index} label={field.label} {...formItemLayout} >
                                        {getFieldDecorator(field.name, field.option)(FieldRender.render(field))}
                                    </FormItem>
                                </Col>
                            );
                        }
                    })}
                </Row>
            </Form >
        );
    }
}

/**
 * 对AutoEidtForm进行一层包装
 */
class EditForm extends React.Component {

    submit(options, callback) {
        this.form.validateFields((err, values) => {
            if (!err) {
                Http.Post(options.url, values).then(() => {
                    message.success('操作成功');
                    if (callback) {
                        callback();
                    }
                }).catch(() => {

                });
            }
        });
    }

    render() {
        const MyForm = Form.create()(AutoEidtForm);
        return <MyForm ref={(form) => this.form = form} {...this.props} />
    }
}

/**
 * 提供增删改查的父类,子类只要实现state里面的几个属性就可以
 */
class Crud extends React.Component {

    state = {
        url: '',

        /*******************搜索框***************** */
        searchField: [],

        /*******************列表***************** */
        columns: [],

        /*******************编辑表单***************** */
        addFields: null,
        editFields: null
    }

    /**
     * 执行数据新增
     */
    onSave = () => {
        this.saveForm.submit({
            url: this.state.url + '/save.json'
        }, () => {
            this.saveModal.destroy();
            this.table.fetch();
        });
        return true;
    }

    /**
     * 执行数据修改
     */
    onUpdate = () => {
        this.editForm.submit({
            url: this.state.url + '/update.json'
        }, () => {
            this.editModal.destroy();
            this.table.fetch();
        });
        return true;
    }

    onAdd = () => {
        this.saveModal = Modal.confirm({
            title: '添加',
            width: this.state.formModalWidth || 600,
            closable: true,
            content: <EditForm ref={(saveForm) => this.saveForm = saveForm} fields={this.state.addFields} />,
            onOk: this.onSave,
            onCancel: (e) => { this.saveModal.destroy() },
            okText: '确认',
            cancelText: '取消'
        });
    }

    /**
     * 点击编辑按钮触发事件
     */
    onEdit = (data) => {

        for (var i = 0; i < this.state.editFields.length; i++) {
            var field = this.state.editFields[i];
            if (!field.option) {
                field.option = {};
            }
            Object.assign(field.option, { initialValue: data[field.name] });
        }

        this.editModal = Modal.confirm({
            title: '编辑',
            width: this.state.formModalWidth || 600,
            closable: true,
            content: <EditForm ref={(form) => this.editForm = form} fields={this.state.editFields} />,
            onOk: this.onUpdate,
            onCancel: (e) => { this.editModal.destroy() },
            okText: '确认',
            cancelText: '取消'
        });
    }

    /**
     * 点击删除按钮触发事件
     */
    onDeletet = (record) => {
        this.deleteModel = Modal.confirm({
            title: '提示',
            closable: true,
            content: `是否要删除该记录?`,
            onOk: () => {
                Http.Post(`${this.state.url}/delete.json`, { id: record.id }).then((data) => {
                    this.deleteModel.destroy();
                    this.table.fetch();
                });
                return true;
            },
            okText: '确认',
            cancelText: '取消'
        });
    }

    /**
     * 点击禁用/启用按钮触发事件
     */
    changeStatus = (status, record) => {
        this.statusModel = Modal.confirm({
            title: '提示',
            closable: true,
            content: `是否要${status == '0' ? '禁用' : '启用'}该记录?`,
            onOk: () => {
                Http.Post(`${this.state.url}/update.json`, { id: record.id, status: status }).then((data) => {
                    this.statusModel.destroy();
                    this.table.fetch();
                });
                return true;
            },
            okText: '确认',
            cancelText: '取消'
        });
    }

    render() {
        return (
            <div>
                <Toolbar fields={this.state.searchField} onSearch={(p) => this.table.fetch(p)} onAdd={this.onAdd} />
                <CrudTable ref={(table) => this.table = table} url={this.state.url + '/page.json'} columns={this.state.columns} />
            </div>
        );
    }
}

export { CrudTable, Toolbar, EditForm, Crud };